<script setup lang="ts">
import { onMounted, watch, nextTick } from 'vue'
import { usePlayerStore } from '@/stores/player'
import type { Music } from '@/stores/player'
import { formatTime } from '@/utils/usertools'
import { getPlaylist, getMusicById, removeFromPlaylist } from '@/api/music'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import 'element-plus/dist/index.css'

const playerStore = usePlayerStore()
const emit = defineEmits(['close'])
const router = useRouter()

const playSong = async (song: Music) => {
  try {
    const musicDetail = await getMusicById(song.id)
    await playerStore.playMusic(musicDetail)
    playerStore.isPlaying = true
  } catch (error) {
    console.error('播放音乐失败:', error)
    ElMessage.error('播放失败')
  }
}

const removeSong = async (song: Music, event: Event) => {
  event.stopPropagation()
  try {
    const result = await removeFromPlaylist(song.id)
    if (result.success) {
      const playlist = await getPlaylist()
      playerStore.playlist = playlist
      
      if (song.id === playerStore.currentMusic.id) {
        if (playlist.length === 0) {
          playerStore.clearPlaylist()
          emit('close')
        } else {
          await playerStore.playMusic(playlist[0])
        }
      }
      
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(result.message || '删除失败')
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const handleClearPlaylist = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空播放列表吗？此操作不可恢复',
      '清空播放列表',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
    )

    const response = await playerStore.clearPlaylist()
    if (response.success) {
      emit('close')
      ElMessage.success('播放列表已清空')
    }
  } catch (error) {
    if (error === 'cancel') {
      return
    }
    
    if (error instanceof Error) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('操作失败')
    }
  }
}

onMounted(async () => {
  try {
    const playlist = await getPlaylist()
    playerStore.setPlaylist(playlist)
  } catch (error) {
    ElMessage.error('获取播放列表失败')
  }
})

watch(
  () => playerStore.currentMusic,
  (newMusic) => {
    nextTick(() => {
      if (playerStore.currentMusic !== newMusic) {
        playerStore.currentMusic = { ...newMusic }
      }
    })
  },
  { deep: true }
)
</script>

<template>
  <div class="playlist-wrapper" @click.self="$emit('close')">
    <div class="playlist-container">
      <div class="playlist-header">
        <div class="header-left">
          <h3>播放列表</h3>
          <span class="song-count" v-if="playerStore.playlist.length">
            ({{ playerStore.playlist.length }}首)
          </span>
        </div>
        <div class="header-right">
          <el-button 
            v-if="playerStore.playlist.length"
            class="clear-btn" 
            @click="handleClearPlaylist"
            type="danger"
            size="small"
            :icon="Delete"
          >
            清空
          </el-button>
          <button class="close-btn" @click="$emit('close')">×</button>
        </div>
      </div>
      <div class="playlist-content">
        <div v-if="!playerStore.playlist.length" class="empty-message">
          暂无歌曲
        </div>
        <div 
          v-else
          v-for="song in playerStore.playlist" 
          :key="song.id"
          class="playlist-item"
          :class="{ active: song.id === playerStore.currentMusic.id }"
          @click="playSong(song)"
        >
          <div class="song-info">
            <div class="song-name">{{ song.title }}</div>
            <div class="artist-name">{{ song.artist }}</div>
          </div>
          <div class="song-actions">
            <span class="song-duration">{{ formatTime(Number(song.duration)) }}</span>
            <el-button
              class="delete-btn"
              @click="removeSong(song, $event)"
              type="danger"
              size="small"
              circle
              :icon="Delete"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.playlist-wrapper {
  position: fixed;
  bottom: 80px;
  right: 20px;
  width: 400px;
  height: 500px;
  background-color: transparent;
  display: flex;
  justify-content: flex-end;
  z-index: 1000;
}

.playlist-container {
  width: 100%;
  height: 100%;
  background-color: var(--bgc-color-2);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
}

.playlist-header {
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);

  .header-left {
    display: flex;
    align-items: center;
    gap: 8px;

    .song-count {
      color: var(--secondary-color);
      font-size: 12px;
      opacity: 0.7;
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .clear-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 6px 12px;
    border: none;
    border-radius: 4px;
    background: rgba(244, 67, 54, 0.1);
    color: #f44336;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.3s ease;

    svg {
      opacity: 0.8;
    }

    &:hover {
      background: rgba(244, 67, 54, 0.2);
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }
  }

  .close-btn {
    background: none;
    border: none;
    color: var(--secondary-color);
    font-size: 20px;
    cursor: pointer;
    padding: 0 4px;

    &:hover {
      color: var(--primary-color);
    }
  }
}

.playlist-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;

  .playlist-item {
    padding: 8px 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    position: relative;
    transition: all 0.3s ease;

    &:hover {
      background-color: rgba(255, 255, 255, 0.05);
    }

    &.active {
      background: linear-gradient(
        to right,
        rgba(255, 255, 255, 0.12),
        rgba(255, 255, 255, 0.08)
      );
      backdrop-filter: blur(8px);
      transform: scale(1.01);
      margin: 4px 0;
      border-radius: 6px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 4px;
        height: 100%;
        background: linear-gradient(
          to bottom,
          var(--theme-color),
          color-mix(in srgb, var(--theme-color) 70%, white)
        );
        border-radius: 4px 0 0 4px;
      }
      
      .song-info {
        .song-name {
          color: #ffffff;
          font-weight: 500;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }
        
        .artist-name {
          color: var(--theme-color);
          opacity: 1;
        }
      }

      .song-actions {
        .song-duration {
          color: var(--theme-color);
        }
        
        .delete-btn {
          opacity: 1;
          color: var(--theme-color);
          
          &:hover {
            transform: scale(1.1);
          }
        }
      }
    }

    .song-info {
      .song-name {
        color: var(--secondary-color);
        font-size: 14px;
        margin-bottom: 4px;
      }

      .artist-name {
        color: var(--secondary-color);
        font-size: 12px;
        opacity: 0.7;
      }
    }

    .song-duration {
      color: var(--secondary-color);
      font-size: 12px;
    }
  }

  .empty-message {
    text-align: center;
    padding: 40px 20px;
    color: var(--secondary-color);
    font-size: 15px;
    font-weight: 500;
  }
}

// 自定义滚动条样式
.playlist-content::-webkit-scrollbar {
  width: 6px;
}

.playlist-content::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.playlist-content::-webkit-scrollbar-track {
  background-color: transparent;
}

@media (max-width: 768px) {
  .playlist-wrapper {
    right: 0;
    width: 100%;
    max-width: 400px;
    margin: 0 10px;
  }
}

.song-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.delete-btn {
  background: none;
  border: none;
  color: var(--secondary-color);
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  opacity: 0;
  transition: opacity 0.2s, color 0.2s;

  &:hover {
    color: var(--theme-color);
  }
}

.playlist-item:hover .delete-btn {
  opacity: 1;
}

// 添加 Element Plus 相关样式覆盖
:deep(.el-button) {
  --el-button-bg-color: transparent;
  --el-button-border-color: transparent;
  --el-button-hover-bg-color: rgba(var(--theme-color), 0.1);
  --el-button-hover-border-color: transparent;
  
  &.clear-btn {
    --el-button-bg-color: rgba(var(--theme-color), 0.1);
    --el-button-text-color: var(--theme-color);
    --el-button-border-color: rgba(var(--theme-color), 0.2);
    --el-button-hover-bg-color: rgba(var(--theme-color), 0.2);
    --el-button-hover-text-color: var(--theme-color);
    --el-button-hover-border-color: rgba(var(--theme-color), 0.3);
  }
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.2s;
}

.playlist-item:hover .delete-btn {
  opacity: 1;
}

// 添加动画
@keyframes pulse {
  0% {
    opacity: 0.5;
    transform: scale(0.95);
  }
  50% {
    opacity: 1;
    transform: scale(1.05);
  }
  100% {
    opacity: 0.5;
    transform: scale(0.95);
  }
}

// 修改歌曲操作按钮在激活状态下的样式
.playlist-item.active {
  .song-actions {
    .song-duration {
      color: var(--theme-color);
    }
    
    .delete-btn {
      opacity: 1;
      color: var(--theme-color);
    }
  }
}
</style>